package com.kedacom.ctsp.authz.security.provider;

import com.kedacom.ctsp.authz.security.util.AccessLoggerConstant;
import com.kedacom.ctsp.logging.AccessLoggerInfo;
import com.kedacom.ctsp.web.utils.WebUtil;
import org.springframework.security.core.Authentication;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * @手动生成AccessLogger
 * @com.kedacom.ctsp.authz.security.provider
 * @fenghaiju
 * @2018/5/7-17:48
 * @cloud-rbac
 **/
public class RestLogoutAccessLoggerSupport {
    private static String METHOD_LOGOUT = "onLogoutSuccess";

    public static AccessLoggerInfo createLogger(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        AccessLoggerInfo info = new AccessLoggerInfo();
        info.setRequestTime(System.currentTimeMillis());
        String action = AccessLoggerConstant.Module.LOGIN_OUT_SUCCESS;
        String describe = AccessLoggerConstant.Module.LOGIN_OUT_SUCCESS;
        info.setAction(action);
        info.setDescribe(describe);

        Map parameters = request.getParameterMap();
        info.setParameters(parameters);
        info.setTarget(RestLogoutSuccessHandler.class);
        try {
            Class<RestLogoutSuccessHandler> clazz = RestLogoutSuccessHandler.class;
            Method method = clazz.getMethod(METHOD_LOGOUT, HttpServletRequest.class, HttpServletResponse.class, Authentication.class);
            info.setMethod(method);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        if (null != request) {
            info.setHttpHeaders(WebUtil.getHeaders(request));
            info.setIp(WebUtil.getIpAddr(request));
            info.setHttpMethod(request.getMethod());
            info.setUrl(request.getRequestURL().toString());
        }
        AuthUserDetails userDetails = (AuthUserDetails) authentication.getPrincipal();

        if (userDetails != null) {

            if (userDetails.getAuthentication() != null) {

                if (userDetails.getAuthentication().getPerson() != null) {
                   // info.setPerson(userDetails.getAuthentication().getPerson());
                }

                if (userDetails.getAuthentication().getUser() != null) {
                  //  info.setUser(userDetails.getAuthentication().getUser());
                }
            }
        }
        info.setResponse(response);
        info.setResponseTime(System.currentTimeMillis());
        return info;
    }

    public static void main(String[] args) {

        try {
            Class clazz = Class.forName("com.kedacom.ctsp.authz.security.provider.RestLogoutSuccessHandler");
            Method method = clazz.getMethod("onLogoutSuccess", HttpServletRequest.class, HttpServletResponse.class, Authentication.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
